﻿Imports System.IO
Imports System.Net.Security
Imports System.Threading

Public Class FileListTree

    Private rootNodeName As String = "ROOT"
    Private listTreeNodes As New ArrayList
    Private tnRoot As New TreeNode(rootNodeName)
    Private isReadDone As Boolean = False
    Private repeatFlg As Boolean = False
    Private pCurrentLocation As Point
    Private isExpanded As Boolean
    Private listNotFound As New ArrayList

    Private Sub btnRead_Click(sender As Object, e As EventArgs) Handles btnRead.Click

        If Not Directory.Exists(Me.txtRoot.Text) Then
            Return
        End If


        Call ReadNewFolder()

    End Sub

    Private Sub ReadNewFolder()

        Me.lblFileCount.Text = "0 件"

        'Dim thd As Thread
        'thd = New Thread(New ThreadStart(AddressOf Reading))
        'CheckForIllegalCrossThreadCalls = False
        'thd.Start()
        Me.tvDir.Nodes.Clear()
        'get roots name
        rootNodeName = GetRootsName()
        tnRoot = New TreeNode(rootNodeName)
        Me.tvDir.Nodes.Add(tnRoot)

        Call NodesCheckedChange(Me.tnRoot, False)
        Call Me.tvDir.CollapseAll()
        Me.listTreeNodes.Clear()
        Call ResetTreeView(tnRoot, Me.txtRoot.Text)

        ' CheckForIllegalCrossThreadCalls = True

    End Sub

    Private Function GetRootsName() As String
        Dim strTmp As String
        strTmp = Me.txtRoot.Text
        Dim idxRoot As Integer
        idxRoot = strTmp.LastIndexOf("\")

        strTmp = strTmp.Substring(idxRoot + 1)

        GetRootsName = strTmp
    End Function

    Private Sub Reading()

        Me.pgb.Minimum = 0
        Me.pgb.Maximum = 10
        Me.pgb.Value = 0

        While Not isReadDone

            Me.pgb.Value = (Me.pgb.Value + 1) Mod 10

        End While

    End Sub

    Private Sub ResetTreeView(ByRef tnParent As TreeNode, ByVal strPath As String)

        Dim mDir As New DirectoryInfo(strPath)

        'サブフォルダ取得
        For Each dObj As DirectoryInfo In mDir.GetDirectories()
            If isIgnoreItem(dObj.Name) Then
                Continue For
            End If
            Dim tn As New TreeNode(dObj.Name)

            Call ResetTreeView(tn, dObj.FullName)
            tn.Name = dObj.Name
            tn.Tag = dObj.FullName
            tnParent.Nodes.Add(tn)

        Next

        'ファイル取得
        For Each dFile As FileInfo In mDir.GetFiles()
            If isIgnoreItem(dFile.Name) Then
                Continue For
            End If
            Dim tn As New TreeNode(dFile.Name)

            tn.Name = dFile.Name
            tn.Tag = dFile.FullName
            tnParent.Nodes.Add(tn)

        Next

    End Sub
    '
    Private Function isIgnoreItem(ByVal strItemName As String)

        Dim isIgnore As Boolean
        isIgnore = False

        Dim ignoreList As New ArrayList
        ignoreList.Add(".")

        For Each strVal As String In ignoreList

            If InStr(strItemName, strVal) = 1 Then
                isIgnore = True
            End If

        Next
        isIgnoreItem = isIgnore
    End Function


    Private Sub btnPreExport_Click(sender As Object, e As EventArgs) Handles btnPreExport.Click

        Dim nodeList As New ArrayList

        For Each node As TreeNode In Me.tvDir.Nodes
            Call PickupCheckedNodes(node, nodeList)
        Next

        Using fileListForm As New FileListForm

            fileListForm.matchingFilePath = Me.txtRoot.Text
            fileListForm.matchingFileList = nodeList
            fileListForm.ShowDialog(Me)

        End Using


    End Sub
    Sub PickupCheckedNodes(ByVal pNode As TreeNode, ByRef nodeList As ArrayList)

        If pNode.Checked And pNode.Nodes.Count = 0 Then
            'nodeList.Add(pNode)

            If File.Exists(pNode.Tag) Then
                Dim mf As New MatchingFile
                mf.fileName = pNode.Text
                mf.filePath.Add(pNode.Tag)
                nodeList.Add(mf)

            End If


        End If
        If pNode.Nodes.Count > 0 Then
            For Each node As TreeNode In pNode.Nodes
                Call PickupCheckedNodes(node, nodeList)
            Next
        End If
    End Sub

    Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        'sai test code
        'Me.txtRoot.Text = "C:\ZeroTools"

        isExpanded = False
        Me.tvDir.Nodes.Clear()
        '位置設定
        Dim screenX As Integer = SystemInformation.PrimaryMonitorSize.Width
        Dim screenY As Integer = SystemInformation.PrimaryMonitorSize.Height
        'Me.Location = New Point(screenX - 900, screenY - 900)
        Me.pCurrentLocation = Me.Location
        Me.Width = 450
        'Call btnExpand_Click(Me.tvDir, New EventArgs)

    End Sub

    Function HasIniFile() As Boolean
        Dim path As String
        path = Application.StartupPath & "\RollCallPresets.ini"


        HasIniFile = True
    End Function


    Private Sub tvDir_AfterCheck(sender As Object, e As TreeViewEventArgs) Handles tvDir.AfterCheck

        If repeatFlg = False Then
            'repeatdefence
            repeatFlg = True
        Else
            e.Node.Checked = Not e.Node.Checked
            Exit Sub
        End If

        Dim tn As TreeView
        tn = sender

        Call NodesCheckedChange(e.Node, e.Node.Checked)

        Dim iCnt As Integer
        iCnt = 0
        Call Calculate_FileCounts(tnRoot, iCnt)
        Me.lblFileCount.Text = iCnt & " 件"

        repeatFlg = False

    End Sub
    Sub NodesCheckedChange(ByRef pNode As TreeNode, ByVal isCheckedType As Boolean)

        If pNode.Nodes.Count > 0 Then
            For Each node As TreeNode In pNode.Nodes
                pNode.Expand()
                pNode.BackColor = Color.Transparent
                Call SetCheckType(pNode, isCheckedType)
                Call NodesCheckedChange(node, isCheckedType)
            Next
        Else
            pNode.BackColor = Color.Transparent
            Call SetCheckType(pNode, isCheckedType)
        End If

    End Sub

    Sub SetCheckType(ByRef pNode As TreeNode, isCheckedType As Boolean)

        RemoveHandler tvDir.AfterCheck, AddressOf tvDir_AfterCheck

        pNode.Checked = isCheckedType

        AddHandler tvDir.AfterCheck, AddressOf tvDir_AfterCheck
    End Sub

    Private Sub Calculate_FileCounts(ByVal pNode As TreeNode, ByRef iCount As Integer)
        If pNode.Nodes.Count > 0 Then
            For Each node As TreeNode In pNode.Nodes

                Call Calculate_FileCounts(node, iCount)
            Next
        Else
            If pNode.Checked = True Then
                iCount = iCount + 1
            End If

        End If
    End Sub

    Private Sub btnExpand_Click(sender As Object, e As EventArgs)

        Call Expand_Form()
    End Sub

    Private Sub txtTarget_TextChanged(sender As Object, e As EventArgs)
        Dim strValue As String
        strValue = sender.text
        If Trim(strValue) = "" Then
            Exit Sub
        End If

        'プログレスバー
        Me.pgb.Minimum = 0
        Me.pgb.Maximum = Me.tvDir.Nodes.Count

        Dim strMatchTarget As String = ""
        Dim strNGTarget As String = ""

        Call NodesCheckedChange(Me.tnRoot, False)
        Me.tvDir.CollapseAll()

        Dim strFiles() As String

        strValue = Replace(strValue, vbCr, vbCrLf)
        strValue = Replace(strValue, vbLf, vbCrLf)

        strFiles = Split(sender.text, vbCrLf)
        Dim listNode As New ArrayList
        Dim iCnt As Integer
        iCnt = 0
        Me.listNotFound.Clear()

        For Each strItem As String In strFiles
            If Trim(strItem) = "" Then
                Continue For
            End If
            Dim iLen As Integer
            iLen = listNode.Count
            Dim iBeforCnt As Integer
            iBeforCnt = iCnt
            Call SearchNode(Me.tvDir.TopNode, strItem, listNode, iCnt)
            Me.lblFileCount.Text = iCnt & " 件"

            If iBeforCnt = iCnt Then
                'not found
                Me.listNotFound.Add(strItem)
            End If

            If iLen = listNode.Count Then
                Continue For
            Else
                strNGTarget = strNGTarget & vbCrLf & strItem
            End If
            strMatchTarget = strMatchTarget & vbCrLf & strItem
        Next

        Dim listPreseteRecord As New ArrayList

        For Each tn As TreeNode In listNode

            tn.BackColor = Color.GreenYellow
            Call SetCheckType(tn, True)

            Dim ptn As New TreeNode
            ptn = tn.Parent
            While Not ptn Is Nothing

                Call ptn.Expand()

                Call SetCheckType(ptn, True)

                ptn = ptn.Parent
            End While

            ' PreseteRecord Make
            Dim pr As New Object
            pr.filePath = New ArrayList
            Dim isMatched As Boolean = False
            For Each pr In listPreseteRecord
                If pr.fileName.Equals(tn.Name) Then
                    isMatched = True
                    listPreseteRecord.Remove(pr)
                    Exit For
                End If
            Next

            If isMatched Then
                pr.isOK = False
                pr.fileName = tn.Name
                pr.filePath.Add(tn.FullPath)
                listPreseteRecord.Add(pr)
            Else
                pr.isOK = True
                pr.fileName = tn.Name
                pr.filePath.Add(tn.FullPath)
                listPreseteRecord.Add(pr)
            End If

            pr = Nothing
        Next

        If Me.listNotFound.Count > 0 Then

            'NotFoundDialog.listNotFound = Me.listNotFound
            'NotFoundDialog.ShowDialog()

            For Each item As String In Me.listNotFound
                Dim pr As New Object
                pr.isOK = False
                pr.fileName = item
                pr.filePath = New ArrayList
                listPreseteRecord.Add(pr)
                pr = Nothing
            Next

            Dim pForm As New Object
            pForm.rootPath = Me.txtRoot.Text
            pForm.rootNodeName = Me.rootNodeName
            pForm.listPreseteRecord = listPreseteRecord

            ' pForm.fType = PresetsForm.FormType.input
            pForm.ShowDialog(Me)

        End If
    End Sub

    Private Sub SearchNode(ByRef pNode As TreeNode, ByVal nodeName As String, ByRef nodeList As ArrayList, ByRef iCnt As Integer)

        If pNode Is Nothing Then
            Exit Sub
        End If

        If pNode.Nodes.Count > 0 Then
            For Each node As TreeNode In pNode.Nodes

                Call SearchNode(node, nodeName, nodeList, iCnt)
            Next
        Else
            ' if nodename is file or directory
            If nodeName.IndexOf("\") > 0 Then   ' has \ 
                'Dim strFullPath As String
                'strFullPath = Me.txtRoot.Text.Substring(0, Me.txtRoot.Text.Length - Me.rootNodeName.Length)

                If pNode.FullPath.ToUpper() = nodeName.ToUpper() Then
                    'If (strFullPath & pNode.FullPath).ToUpper() = nodeName.ToUpper() Then

                    nodeList.Add(pNode)
                    iCnt = iCnt + 1
                End If

            Else                            ' has not \
                If pNode.Name.ToUpper() = nodeName.ToUpper() Then
                    nodeList.Add(pNode)
                    iCnt = iCnt + 1
                End If
            End If

        End If

    End Sub

    Private Sub txtRoot_DoubleClick(sender As Object, e As EventArgs) Handles txtRoot.DoubleClick

        Dim strResult As String
        strResult = FolderBrowserDialog1.ShowDialog(Me)

        If Not txtRoot.Text = FolderBrowserDialog1.SelectedPath And Not Trim(FolderBrowserDialog1.SelectedPath) = "" Then

            txtRoot.Text = FolderBrowserDialog1.SelectedPath
            Call ReadNewFolder()

        End If


    End Sub


    Private Sub tvDir_DragDrop(sender As Object, e As DragEventArgs) Handles tvDir.DragDrop

        'MsgBox("tvDir_DragDrop" & e.Effect)

    End Sub

    Private Sub tvDir_DragEnter(sender As Object, e As DragEventArgs) Handles tvDir.DragEnter

        'MsgBox("tvDir_DragEnter" & e.Data.GetDataPresent(DataFormats.Text))
    End Sub

    Private Sub tsmiCheckByTarget_Click(sender As Object, e As EventArgs) Handles tsmiCheckByTarget.Click

        Call btnExpand_Click(Me.tvDir, New EventArgs)

    End Sub

    Private Sub tmrRepeatDefence_Tick(sender As Object, e As EventArgs) Handles tmrRepeatDefence.Tick

    End Sub

    Private Sub btnTop_Click(sender As Object, e As EventArgs) Handles btnTop.Click
        Me.tvDir.SelectedNode = tnRoot
        Me.tvDir.SelectedNode = Nothing
    End Sub

    Private Sub MainForm_Move(sender As Object, e As EventArgs) Handles Me.Move
        Me.pCurrentLocation = sender.location
    End Sub

    Private Sub btnSearch_MouseDown(sender As Object, e As MouseEventArgs)

    End Sub

    Private Sub btnSearch_MouseUp(sender As Object, e As MouseEventArgs)

    End Sub

    Private Sub txtRoot_TextChanged(sender As Object, e As EventArgs) Handles txtRoot.TextChanged

    End Sub

    Private Sub btnSearch_Click(sender As Object, e As EventArgs)

        Call Expand_Form()

    End Sub

    Private Sub Expand_Form()
        Me.Location = Me.pCurrentLocation

        If isExpanded = True Then
            Me.Width = 450
            isExpanded = False
        Else
            Me.Width = 1200
            isExpanded = True
        End If

    End Sub


End Class
